//
//  FSCategoryVC.m
//  FieldStory
//
//  Created by itte on 2017/6/22.
//  Copyright © 2017年 funmain. All rights reserved.
//

#import "FSCategoryVC.h"
#import "CategoryCltCell.h"
#import "SubCategoryCltCell.h"

#define cellWidth    (SCREEN_WIDTH-40)/2

@interface FSCategoryVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *cltContentView;
@property (strong, nonatomic) IBOutlet UIView *maskView;
@property (weak, nonatomic) IBOutlet UICollectionView *cltSubCategoryView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lcsSubCategoryTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lcsImgUpCenter;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lcsImgDownCenter;
@property (weak, nonatomic) IBOutlet UIImageView *imgUp;
@property (weak, nonatomic) IBOutlet UIImageView *imgDown;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableArray *dataSubArray;
@property (assign, nonatomic) NSInteger indexOfSelect;

@end

@implementation FSCategoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择品类";
    [self.cltContentView registerNib:[UINib nibWithNibName:@"CategoryCltCell" bundle:nil] forCellWithReuseIdentifier:@"CategoryCltCellID"];
    [self.cltSubCategoryView registerNib:[UINib nibWithNibName:@"SubCategoryCltCell" bundle:nil] forCellWithReuseIdentifier:@"SubCategoryCltCellID"];
    self.cltContentView.delegate = self;
    self.cltContentView.dataSource = self;
    self.cltSubCategoryView.delegate = self;
    self.cltSubCategoryView.dataSource = self;
    self.indexOfSelect = -1;
    
    self.maskView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.6];
    [self.view addSubview:self.maskView];
    [self.view sendSubviewToBack:self.maskView];
    WeakSelfType blockSelf = self;
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(blockSelf.view);
    }];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMaskView)];
    tapGesture.delegate = self;
    [self.maskView addGestureRecognizer:tapGesture];
    [self getCateLists];
}

#pragma mark - 网络获取数据
-(void)getCateLists
{
    WeakSelfType blockSelf = self;
    [[AFNetworkManager sharedInstance] httpGetWithUrl:@"cate/getChildCateLists" params:nil showHUD:YES toShowHUDView:self.view success:^(id responseObject, NSString *errorMessage) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *data = [FSCategoryModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [blockSelf.dataArray removeAllObjects];
            [blockSelf.dataArray addObjectsFromArray:data];
            [blockSelf.cltContentView reloadData];
        }
    } fail:^(NSString *errorCode, NSString *errorMessage) {
        
    }];
}

-(void)getSubCateLists:(NSInteger)ID
{
    WeakSelfType blockSelf = self;
    NSString *api = [NSString stringWithFormat:@"goods/%ld",ID];
    [[AFNetworkManager sharedInstance] httpGetWithUrl:api params:nil showHUD:YES toShowHUDView:self.view success:^(id responseObject, NSString *errorMessage) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *data = [FSSubCategoryModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [blockSelf.dataSubArray removeAllObjects];
            [blockSelf.dataSubArray addObjectsFromArray:data];
            [blockSelf.cltSubCategoryView reloadData];
        }
    } fail:^(NSString *errorCode, NSString *errorMessage) {
        
    }];
}

-(void)hideMaskView
{
    self.indexOfSelect = -1;
    [self.view sendSubviewToBack:self.maskView];
     [self.cltContentView reloadData];
}

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)dataSubArray
{
    if (_dataSubArray == nil) {
        _dataSubArray = [NSMutableArray array];
    }
    return _dataSubArray;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:self.cltSubCategoryView]) {
        return NO;
    }
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    if (1000 == collectionView.tag) {
        return self.dataArray.count;
    }
    else{
        return self.dataSubArray.count;
    }
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (1000 == collectionView.tag) {
        CategoryCltCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CategoryCltCellID" forIndexPath:indexPath];
        FSCategoryModel *category = self.dataArray[indexPath.item];
        [cell.imgProduct sd_setImageWithURL:[NSURL URLWithString:category.images] placeholderImage:[UIImage imageNamed:@"icon_wx"]];
        cell.lbName.text = category.name;
        cell.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
        cell.layer.borderWidth = 0.6f;
        if (self.indexOfSelect >= 0 && self.indexOfSelect != indexPath.row) {
            cell.lcsAlphaHeight.constant = cellWidth+20;
        }
        else{
            cell.lcsAlphaHeight.constant = 0;
        }
        return cell;
    }
    else {
        SubCategoryCltCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SubCategoryCltCellID" forIndexPath:indexPath];
        FSSubCategoryModel *subCategory = self.dataSubArray[indexPath.item];
        [cell.imgProduct sd_setImageWithURL:[NSURL URLWithString:subCategory.images] placeholderImage:[UIImage imageNamed:@"icon_wx"]];
        cell.lbName.text = subCategory.name;
        cell.lbPrice.text = [NSString stringWithFormat:@"￥%@",subCategory.price];
        cell.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
        cell.layer.borderWidth = 0.6f;
        return cell;
    }

    
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (1000 == collectionView.tag) {
        return CGSizeMake(cellWidth, cellWidth+20);
    }
    else if (2000 == collectionView.tag){
        return CGSizeMake(120, 150);
    }
    return CGSizeMake(120, 150);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"-- %ld --",indexPath.row);
    if (1000 == collectionView.tag) {
        self.indexOfSelect = indexPath.row;
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        CGPoint point = [self.view convertPoint:cell.center fromView:collectionView];
        NSLog(@"cell center point y: %f",point.y);
        [self.cltContentView reloadData];
        [self showSubCategory:point];
        [self getSubCateLists:indexPath.item];
    }
    else{
        NSLog(@"-- other --");
        [self hideMaskView];
        NSDictionary *dictParam = @{@"data":self.dataSubArray,@"index":@(indexPath.item)};
        [self pushViewController:@"FSCategoryDetailVC" withParams:dictParam];
    }
}

-(void)showSubCategory:(CGPoint)center
{
    CGFloat topY = center.y - (cellWidth+20) * 0.5;
    CGFloat bottomY = center.y + (cellWidth+20) * 0.5;
    
    if (171 > (self.view.height - bottomY)) {
        [self.imgUp setHidden:YES];
        [self.imgDown setHidden:NO];
        self.lcsImgDownCenter.constant =  center.x - self.view.centerX;
        self.lcsSubCategoryTop.constant = topY-171;
    }
    else{
        [self.imgUp setHidden:NO];
        [self.imgDown setHidden:YES];
        self.lcsImgUpCenter.constant = center.x - self.view.centerX;
        self.lcsSubCategoryTop.constant = bottomY+21;
    }
    [self.view bringSubviewToFront:self.maskView];
}

@end
